import os
import sys
import json
import random
from datetime import datetime, timedelta

current_dir = os.path.dirname(os.path.abspath(__file__))
project_root = os.path.abspath(os.path.join(current_dir, '..'))
sys.path.insert(0, project_root)

from core.database import Database


def generate_players(count=100):
    games = ['王者荣耀', 'LOL', '和平精英', '原神', 'CSGO', '永劫无间']
    voice_types = ['御姐', '少女', '萝莉', '大叔', '正太']
    tags_pool = ['技术好', '声音甜', '会聊天', '温柔', '幽默', '高效', '耐心', '专业']
    
    players = []
    
    for i in range(1, count + 1):
        player = {
            'player_id': 1000 + i,
            'nickname': f"陪玩师{i}号",
            'games': random.sample(games, k=random.randint(1, 3)),
            'voice_type': random.choice(voice_types),
            'price': random.choice([5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100]),
            'rating': round(random.uniform(4.0, 5.0), 1),
            'tags': random.sample(tags_pool, k=random.randint(2, 4)),
            'description': f"专业{random.choice(games)}陪玩，经验丰富",
            'is_new': i <= 10,
            'response_time': random.randint(1, 15),
            'accept_rate': round(random.uniform(0.7, 0.98), 2),
            'online': random.choice([True, True, True, False]),
            'total_orders': random.randint(0, 1000) if i > 10 else random.randint(0, 50),
            'is_blocked': False
        }
        
        if i <= 5:
            player['nickname'] = f"明星陪玩{i}"
            player['rating'] = 4.9
            player['price'] = random.choice([70, 75, 80, 85, 90, 95, 100])
            player['total_orders'] = 500 + i * 100
            player['accept_rate'] = 0.95
            player['response_time'] = 2
        
        players.append(player)
    
    return players


def generate_users(count=50):
    games = ['王者荣耀', 'LOL', '和平精英']
    voice_types = ['御姐', '少女', '萝莉']
    
    users = []
    
    for i in range(1, count + 1):
        user = {
            'user_id': 1000 + i,
            'username': f"用户{i}",
            'register_time': (datetime.now() - timedelta(days=random.randint(1, 365))).isoformat(),
            'total_orders': random.randint(0, 50),
            'avg_price': random.choice([25, 30, 35, 40, 45]),
            'favorite_games': random.sample(games, k=random.randint(1, 2)),
            'preferred_voice': random.choice(voice_types),
            'blacklist': [],
            'recent_players': [],
            'interest_games': random.sample(games, k=2) if i <= 10 else [],
            'last_active': (datetime.now() - timedelta(days=random.randint(0, 30))).isoformat()
        }
        
        if i <= 10:
            user['total_orders'] = 0
            user['avg_price'] = 30
        
        users.append(user)
    
    return users


def generate_orders(players, users, count=200):
    games = ['王者荣耀', 'LOL', '和平精英', '原神', 'CSGO', '永劫无间']
    orders = []
    
    for i in range(1, count + 1):
        player = random.choice(players)
        order = {
            'user_id': random.choice(users)['user_id'],
            'player_id': player['player_id'],
            'game': random.choice(player.get('games', games)),  # 从陪玩师支持的游戏中选择
            'price': player.get('price', random.choice([20, 30, 40, 50])),  # 使用陪玩师的价格
            'duration': random.choice([1, 2, 3, 4]),  # 订单时长（小时）
            'rating': round(random.uniform(4.0, 5.0), 1),
            'order_time': (datetime.now() - timedelta(hours=random.randint(1, 720))).isoformat()
        }
        orders.append(order)
    
    return orders


def save_data():
    print("[INFO] Generating sample data...")
    
    db = Database()
    
    players = generate_players(300)
    users = generate_users(50)
    orders = generate_orders(players, users, 500)
    
    print(f"[INFO] Inserting {len(players)} players...")
    for player in players:
        db.insert_player(player)
    print(f"[INFO] Inserted {len(players)} players")
    
    print(f"[INFO] Inserting {len(users)} users...")
    for user in users:
        db.insert_user(user)
    print(f"[INFO] Inserted {len(users)} users")
    
    print(f"[INFO] Inserting {len(orders)} orders...")
    for order in orders:
        db.insert_order(order)
    print(f"[INFO] Inserted {len(orders)} orders")
    
    db.close()
    print(f"\n[INFO] Data saved to database: data/companion.db")


if __name__ == "__main__":
    save_data()


